import axios from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";

const request = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

request.interceptors.request.use(
  (config) => {
    // 获取用户仓库
    let userStore = useUserStore();
    if (userStore.userInfo.token) {
      config.headers.token = userStore.userInfo.token;
    }
    // 在发送请求之前做些什么
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 处理http网络请求错误
    console.log(error);
    let status = error.response.status;
    console.log(status);
    switch (status) {
      case 404:
        // 错误提示信息
        ElMessage({
          message: error.message,
          type: "error",
        });
        break;
      case 500 | 501 | 502 | 503 | 504 | 505:
        ElMessage({
          message: "服务器已崩溃",
          type: "error",
        });
        break;
      case 401:
        ElMessage({
          message: "请求参数有误",
          type: "error",
        });
        break;
    }
    return Promise.reject(error);
  }
);

export default request;
